"""
管理员路由模块
处理管理员功能，包括用户管理、系统监控、邮件管理等
"""
from datetime import datetime, timedelta
from flask import render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from functools import wraps
from app.admin import bp
from app.models import User, Email
from app import db
from sqlalchemy import func, desc, or_

def admin_required(f):
    """
    管理员权限装饰器
    
    Args:
        f: 被装饰的函数
    
    Returns:
        装饰后的函数
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated or not current_user.is_admin():
            if request.is_json:
                return jsonify({'success': False, 'message': '需要管理员权限'}), 403
            flash('需要管理员权限才能访问此页面', 'error')
            return redirect(url_for('main.index'))
        return f(*args, **kwargs)
    return decorated_function

@bp.route('/dashboard')
@login_required
@admin_required
def dashboard():
    """
    管理员仪表板
    显示系统概览和统计信息
    """
    try:
        # 用户统计
        total_users = User.query.count()
        active_users = User.query.filter_by(is_active=True).count()
        admin_users = User.query.filter_by(role='admin').count()
        student_users = User.query.filter_by(role='student').count()
        
        # 邮件统计
        total_emails = Email.query.count()
        today = datetime.utcnow().date()
        today_emails = Email.query.filter(
            func.date(Email.sent_at) == today
        ).count()
        
        # 最近7天的邮件统计
        week_ago = datetime.utcnow() - timedelta(days=7)
        week_emails = Email.query.filter(
            Email.sent_at >= week_ago
        ).count()
        
        # 未读邮件统计
        unread_emails = Email.query.filter_by(is_read=False).count()
        
        # 最近注册的用户
        recent_users = User.query.order_by(desc(User.created_at)).limit(5).all()
        
        # 最近的邮件
        recent_emails = Email.query.order_by(desc(Email.sent_at)).limit(10).all()
        
        stats = {
            'users': {
                'total': total_users,
                'active': active_users,
                'admin': admin_users,
                'student': student_users
            },
            'emails': {
                'total': total_emails,
                'today': today_emails,
                'week': week_emails,
                'unread': unread_emails
            }
        }
        
        return render_template('admin/dashboard.html', 
                             title='管理员仪表板',
                             stats=stats,
                             recent_users=recent_users,
                             recent_emails=recent_emails,
                             datetime=datetime)
        
    except Exception as e:
        flash(f'加载仪表板失败：{str(e)}', 'error')
        return redirect(url_for('main.index'))

@bp.route('/users')
@login_required
@admin_required
def users():
    """
    用户管理页面
    显示所有用户列表
    """
    try:
        page = request.args.get('page', 1, type=int)
        search = request.args.get('search', '').strip()
        role_filter = request.args.get('role', '')
        status_filter = request.args.get('status', '')
        class_filter = request.args.get('class', '').strip()
        
        # 构建查询
        query = User.query
        
        # 搜索功能
        if search:
            query = query.filter(
                or_(
                    User.username.contains(search),
                    User.email.contains(search),
                    User.real_name.contains(search)
                )
            )
        
        # 角色筛选
        if role_filter:
            query = query.filter_by(role=role_filter)
        
        # 状态筛选
        if status_filter == 'active':
            query = query.filter_by(is_active=True)
        elif status_filter == 'inactive':
            query = query.filter_by(is_active=False)
        
        # 班级筛选
        if class_filter:
            try:
                class_id = int(class_filter)
                query = query.filter_by(class_id=class_id)
            except ValueError:
                # 如果转换失败，忽略筛选
                pass
        
        # 分页
        users = query.order_by(desc(User.created_at)).paginate(
            page=page, per_page=20, error_out=False
        )
        
        # 获取所有班级列表用于筛选（0-10）
        class_options = []
        for i in range(11):  # 0-10
            if i == 0:
                class_options.append({'id': i, 'name': '其他班级'})
            else:
                class_options.append({'id': i, 'name': f'{i}班'})
        
        return render_template('admin/users.html',
                             title='用户管理',
                             users=users,
                             search=search,
                             role_filter=role_filter,
                             status_filter=status_filter,
                             class_filter=class_filter,
                             class_options=class_options)
        
    except Exception as e:
        flash(f'加载用户列表失败：{str(e)}', 'error')
        return redirect(url_for('admin.dashboard'))

@bp.route('/users/<int:user_id>')
@login_required
@admin_required
def user_detail(user_id):
    """
    用户详情页面
    
    Args:
        user_id: 用户ID
    """
    try:
        user = User.query.get_or_404(user_id)
        
        # 用户邮件统计
        sent_count = Email.query.filter_by(sender_id=user.id).count()
        received_count = Email.query.filter_by(recipient_id=user.id).count()
        
        # 最近发送的邮件
        recent_sent = Email.query.filter_by(sender_id=user.id)\
                                .order_by(desc(Email.sent_at)).limit(5).all()
        
        # 最近接收的邮件
        recent_received = Email.query.filter_by(recipient_id=user.id)\
                                    .order_by(desc(Email.sent_at)).limit(5).all()
        
        return render_template('admin/user_detail.html',
                             title=f'用户详情 - {user.username}',
                             user=user,
                             sent_count=sent_count,
                             received_count=received_count,
                             recent_sent=recent_sent,
                             recent_received=recent_received)
        
    except Exception as e:
        flash(f'加载用户详情失败：{str(e)}', 'error')
        return redirect(url_for('admin.users'))

@bp.route('/users/<int:user_id>/toggle_status', methods=['POST'])
@login_required
@admin_required
def toggle_user_status(user_id):
    """
    切换用户状态（启用/禁用）
    
    Args:
        user_id: 用户ID
    """
    try:
        user = User.query.get_or_404(user_id)
        
        # 不能禁用自己
        if user.id == current_user.id:
            return jsonify({'success': False, 'message': '不能禁用自己的账号'}), 400
        
        # 切换状态
        user.is_active = not user.is_active
        db.session.commit()
        
        status_text = '启用' if user.is_active else '禁用'
        return jsonify({
            'success': True, 
            'message': f'用户 {user.username} 已{status_text}',
            'is_active': user.is_active
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'操作失败：{str(e)}'}), 500

@bp.route('/users/<int:user_id>/change_role', methods=['POST'])
@login_required
@admin_required
def change_user_role(user_id):
    """
    修改用户角色
    
    Args:
        user_id: 用户ID
    """
    try:
        user = User.query.get_or_404(user_id)
        data = request.get_json()
        new_role = data.get('role')
        
        if new_role not in ['admin', 'student']:
            return jsonify({'success': False, 'message': '无效的角色'}), 400
        
        # 不能修改自己的角色
        if user.id == current_user.id:
            return jsonify({'success': False, 'message': '不能修改自己的角色'}), 400
        
        old_role = user.role
        user.role = new_role
        db.session.commit()
        
        return jsonify({
            'success': True, 
            'message': f'用户 {user.username} 的角色已从 {old_role} 修改为 {new_role}',
            'role': new_role
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'修改失败：{str(e)}'}), 500

@bp.route('/users/<int:user_id>/reset_password', methods=['POST'])
@login_required
@admin_required
def reset_user_password(user_id):
    """
    重置用户密码为默认密码123456
    
    Args:
        user_id: 用户ID
    """
    try:
        user = User.query.get_or_404(user_id)
        
        # 不能重置自己的密码
        if user.id == current_user.id:
            return jsonify({'success': False, 'message': '不能重置自己的密码'}), 400
        
        # 重置为默认密码
        default_password = '123456'
        user.set_password(default_password)
        db.session.commit()
        
        return jsonify({
            'success': True, 
            'message': f'用户 {user.username} 的密码已重置为默认密码'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'重置失败：{str(e)}'}), 500

@bp.route('/emails')
@login_required
@admin_required
def emails():
    """
    邮件管理页面
    显示所有邮件列表
    """
    try:
        page = request.args.get('page', 1, type=int)
        search = request.args.get('search', '').strip()
        
        # 构建查询
        query = Email.query
        
        # 搜索功能
        if search:
            query = query.filter(
                or_(
                    Email.subject.contains(search),
                    Email.content.contains(search)
                )
            )
        
        # 分页
        emails = query.order_by(desc(Email.sent_at)).paginate(
            page=page, per_page=20, error_out=False
        )
        
        return render_template('admin/emails.html',
                             title='邮件管理',
                             emails=emails,
                             search=search)
        
    except Exception as e:
        flash(f'加载邮件列表失败：{str(e)}', 'error')
        return redirect(url_for('admin.dashboard'))

@bp.route('/emails/<int:email_id>')
@login_required
@admin_required
def email_detail(email_id):
    """
    邮件详情页面
    
    Args:
        email_id: 邮件ID
    """
    try:
        email = Email.query.get_or_404(email_id)
        
        return render_template('admin/email_detail.html',
                             title=f'邮件详情 - {email.subject}',
                             email=email)
        
    except Exception as e:
        flash(f'加载邮件详情失败：{str(e)}', 'error')
        return redirect(url_for('admin.emails'))

@bp.route('/emails/<int:email_id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_email(email_id):
    """
    管理员删除邮件（物理删除）
    
    Args:
        email_id: 邮件ID
    """
    try:
        email = Email.query.get_or_404(email_id)
        
        subject = email.subject
        db.session.delete(email)
        db.session.commit()
        
        return jsonify({
            'success': True, 
            'message': f'邮件 "{subject}" 已删除'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'删除失败：{str(e)}'}), 500

@bp.route('/stats/api')
@login_required
@admin_required
def stats_api():
    """
    获取系统统计数据API
    """
    try:
        # 最近7天的邮件发送统计
        days_data = []
        for i in range(7):
            date = datetime.utcnow().date() - timedelta(days=i)
            count = Email.query.filter(
                func.date(Email.sent_at) == date
            ).count()
            days_data.append({
                'date': date.strftime('%Y-%m-%d'),
                'count': count
            })
        
        # 用户角色分布
        role_stats = db.session.query(
            User.role, func.count(User.id)
        ).group_by(User.role).all()
        
        role_data = [{'role': role, 'count': count} for role, count in role_stats]
        
        # 用户状态分布
        active_count = User.query.filter_by(is_active=True).count()
        inactive_count = User.query.filter_by(is_active=False).count()
        
        status_data = [
            {'status': '活跃', 'count': active_count},
            {'status': '禁用', 'count': inactive_count}
        ]
        
        return jsonify({
            'success': True,
            'data': {
                'daily_emails': list(reversed(days_data)),
                'role_distribution': role_data,
                'status_distribution': status_data
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取统计失败：{str(e)}'}), 500

@bp.route('/system/cleanup', methods=['POST'])
@login_required
@admin_required
def system_cleanup():
    """
    系统清理功能
    清理已删除的邮件等
    """
    try:
        # 清理双方都删除的邮件
        deleted_emails = Email.query.filter(
            Email.is_deleted_by_sender == True,
            Email.is_deleted_by_recipient == True
        ).all()
        
        count = len(deleted_emails)
        for email in deleted_emails:
            db.session.delete(email)
        
        db.session.commit()
        
        return jsonify({
            'success': True, 
            'message': f'系统清理完成，删除了 {count} 封邮件'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'清理失败：{str(e)}'}), 500